package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.vilyever.drawingview.DrawingView;
import com.vilyever.drawingview.brush.drawing.PenBrush;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.ActivityDrawBinding;
import flc.ast.dialog.ColorDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class DrawActivity extends BaseAc<ActivityDrawBinding> {

    public static int img;
    public static int imgBg;
    public static boolean isNew;
    public static int type;
    private PenBrush penBrush;
    private int paintWidth = 15;//画笔宽度
    private int eraserWidth = 15;//橡皮擦宽度
    private ColorAdapter brushColorAdapter, bgColorAdapter;
    private int oldColorPos1 = 0, oldColorPos2 = 0;
    private String mSelectColor;
    private String mSelectBgColor;
    private ColorDialog myColorDialog, myBgColorDialog;
    private Dialog myTipDialog;
    private boolean isSelected = false, isBgSelected = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_draw;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivDrawBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivDrawBrushNew.setOnClickListener(this);
        mDataBinding.ivDrawEraserNew.setOnClickListener(this);
        mDataBinding.ivDrawColorNew.setOnClickListener(this);
        mDataBinding.ivDrawBackground.setOnClickListener(this);
        mDataBinding.ivDrawBrush.setOnClickListener(this);
        mDataBinding.ivDrawEraser.setOnClickListener(this);
        mDataBinding.ivDrawColor.setOnClickListener(this);
        mDataBinding.ivDrawRecover.setOnClickListener(this);
        mDataBinding.ivDrawRevocation.setOnClickListener(this);
        mDataBinding.ivDrawClear.setOnClickListener(this);
        mDataBinding.ivDrawSave.setOnClickListener(this);
        mDataBinding.ivColorSelNew.setOnClickListener(this);
        mDataBinding.ivColorSel.setOnClickListener(this);
        mDataBinding.ivBgColorSel.setOnClickListener(this);
        mDataBinding.myDrawingView.setUndoRedoStateDelegate(new DrawingView.UndoRedoStateDelegate() {
            @Override
            public void onUndoRedoStateChange(DrawingView drawingView, boolean canUndo, boolean canRedo) {
                if (canUndo) {
                    mDataBinding.ivDrawRevocation.setImageResource(R.drawable.tui2);
                } else {
                    mDataBinding.ivDrawRevocation.setImageResource(R.drawable.tui1);
                }
                if (canRedo) {
                    mDataBinding.ivDrawRecover.setImageResource(R.drawable.jin2);
                } else {
                    mDataBinding.ivDrawRecover.setImageResource(R.drawable.jin1);
                }
            }
        });
        if (isNew || type == 1) {
            //新建画板画笔颜色
            mDataBinding.rvBrushColorNewList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
            brushColorAdapter = new ColorAdapter();
            mDataBinding.rvBrushColorNewList.setAdapter(brushColorAdapter);
            brushColorAdapter.setOnItemClickListener(this);
            //背景颜色
            mDataBinding.rvBgColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
            bgColorAdapter = new ColorAdapter();
            mDataBinding.rvBgColorList.setAdapter(bgColorAdapter);
            bgColorAdapter.setOnItemClickListener(this);
        } else {
            //画笔颜色
            mDataBinding.rvBrushColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
            brushColorAdapter = new ColorAdapter();
            mDataBinding.rvBrushColorList.setAdapter(brushColorAdapter);
            brushColorAdapter.setOnItemClickListener(this);
        }
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDrawBrushNew://新建画板画笔
                penBrush.setIsEraser(false);
                penBrush.setSize(paintWidth);
                clearSelectionNew();
                mDataBinding.seekbarBrushNew.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawEraserNew://新建画板橡皮
                penBrush.setIsEraser(true);
                penBrush.setSize(eraserWidth);
                clearSelectionNew();
                mDataBinding.seekbarEraserNew.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawColorNew://新建画板画笔颜色
                clearSelectionNew();
                mDataBinding.llColorSelNew.setVisibility(View.VISIBLE);
                break;
            case R.id.ivColorSelNew://画笔自定义颜色
            case R.id.ivColorSel:
                myColorDialog.show();
                myColorDialog.setListener(new ColorDialog.IListener() {
                    @Override
                    public void onClickConfirm(String color) {
                        mSelectColor = color;
                        penBrush.setColor(Color.parseColor(mSelectColor));
                        if (isNew || type == 1) {
                            mDataBinding.tvColorSelNew.setVisibility(View.VISIBLE);
                        } else {
                            mDataBinding.tvColorSel.setVisibility(View.VISIBLE);
                        }
                        isSelected = true;
                        brushColorAdapter.getItem(oldColorPos1).setSelect(false);
                        brushColorAdapter.notifyItemChanged(oldColorPos1);
                    }
                });
                break;
            case R.id.ivDrawBackground://背景颜色
                clearSelectionNew();
                mDataBinding.llBgColorSel.setVisibility(View.VISIBLE);
                break;
            case R.id.ivBgColorSel://背景自定义颜色
                myBgColorDialog.show();
                myBgColorDialog.setListener(new ColorDialog.IListener() {
                    @Override
                    public void onClickConfirm(String color) {
                        mDataBinding.rlDrawSave.setBackgroundColor(Color.parseColor(color));
                        mDataBinding.tvBgColorSel.setVisibility(View.VISIBLE);
                        isBgSelected = true;
                        bgColorAdapter.getItem(oldColorPos2).setSelect(false);
                        bgColorAdapter.notifyItemChanged(oldColorPos2);
                    }
                });
                break;
            case R.id.ivDrawBrush://画板画笔
                penBrush.setIsEraser(false);
                penBrush.setSize(paintWidth);
                clearSelection();
                mDataBinding.seekbarBrush.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawEraser://画板橡皮
                penBrush.setIsEraser(true);
                penBrush.setSize(eraserWidth);
                clearSelection();
                mDataBinding.seekbarEraser.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawColor://画板画笔颜色
                clearSelection();
                mDataBinding.llColorSel.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawRecover://复原
                mDataBinding.myDrawingView.redo();
                break;
            case R.id.ivDrawRevocation://撤回
                mDataBinding.myDrawingView.undo();
                break;
            case R.id.ivDrawSave://保存
                saveImg();
                break;
            case R.id.ivDrawClear://刷新
                mDataBinding.myDrawingView.clear();
                break;
            //提示弹框
            case R.id.ivDialogTipSave://退出并保存
                saveImg();
                myTipDialog.dismiss();
                break;
            case R.id.ivDialogTipExit://直接退出
                myTipDialog.dismiss();
                finish();
                break;
            case R.id.ivDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == brushColorAdapter) {
            if (isSelected) {
                isSelected = false;
                if (isNew || type == 1) {
                    mDataBinding.tvColorSelNew.setVisibility(View.GONE);
                } else {
                    mDataBinding.tvColorSel.setVisibility(View.GONE);
                }
            }
            brushColorAdapter.getItem(oldColorPos1).setSelect(false);
            oldColorPos1 = position;
            brushColorAdapter.getItem(position).setSelect(true);
            brushColorAdapter.notifyDataSetChanged();
            penBrush.setColor(Color.parseColor(brushColorAdapter.getItem(position).getColor()));//默认画笔颜色
        } else {
            if (isBgSelected) {
                isBgSelected = false;
                mDataBinding.tvBgColorSel.setVisibility(View.GONE);
            }
            bgColorAdapter.getItem(oldColorPos2).setSelect(false);
            oldColorPos2 = position;
            bgColorAdapter.getItem(position).setSelect(true);
            bgColorAdapter.notifyDataSetChanged();
            mDataBinding.rlDrawSave.setBackgroundColor(Color.parseColor(bgColorAdapter.getItem(position).getColor()));//默认背景颜色
        }
    }

    @Override
    protected void initData() {
        //画笔颜色
        List<MyColorBean> listBrushColor = new ArrayList<>();
        listBrushColor.add(new MyColorBean("#333333", true));
        listBrushColor.add(new MyColorBean("#D8D8D8", false));
        listBrushColor.add(new MyColorBean("#D0B5A4", false));
        listBrushColor.add(new MyColorBean("#F5C6BF", false));
        listBrushColor.add(new MyColorBean("#FA8EA5", false));
        listBrushColor.add(new MyColorBean("#B17DD2", false));
        listBrushColor.add(new MyColorBean("#A5201B", false));
        listBrushColor.add(new MyColorBean("#5FBC8F", false));
        listBrushColor.add(new MyColorBean("#3F68BC", false));
        listBrushColor.add(new MyColorBean("#9F45F1", false));
        listBrushColor.add(new MyColorBean("#E85C90", false));
        listBrushColor.add(new MyColorBean("#C0C0C0", false));
        brushColorAdapter.setList(listBrushColor);
        myColorDialog = new ColorDialog(mContext);
        if (isNew || type == 1) {
            initPenNew();
            //背景颜色
            List<MyColorBean> listBgColor = new ArrayList<>();
            listBgColor.add(new MyColorBean("#FFFFFF", true));
            listBgColor.add(new MyColorBean("#D8D8D8", false));
            listBgColor.add(new MyColorBean("#D0B5A4", false));
            listBgColor.add(new MyColorBean("#F5C6BF", false));
            listBgColor.add(new MyColorBean("#FA8EA5", false));
            listBgColor.add(new MyColorBean("#B17DD2", false));
            listBgColor.add(new MyColorBean("#A5201B", false));
            listBgColor.add(new MyColorBean("#5FBC8F", false));
            listBgColor.add(new MyColorBean("#3F68BC", false));
            listBgColor.add(new MyColorBean("#9F45F1", false));
            listBgColor.add(new MyColorBean("#E85C90", false));
            listBgColor.add(new MyColorBean("#C0C0C0", false));
            bgColorAdapter.setList(listBgColor);
            myBgColorDialog = new ColorDialog(mContext);
        } else {
            initPen();
            mDataBinding.llDrawBottomNew.setVisibility(View.GONE);
            mDataBinding.llDrawBottom.setVisibility(View.VISIBLE);
            mDataBinding.ivDrawImgBg.setImageResource(imgBg);
            mDataBinding.ivDrawImg.setImageResource(img);
        }
        if (type == 1) {
            mDataBinding.ivDrawImgBg.setImageResource(imgBg);
        }
    }

    //新建画板初始化画笔
    private void initPenNew() {
        penBrush = PenBrush.defaultBrush();
        penBrush.setColor(Color.parseColor("#333333"));//默认画笔颜色
        penBrush.setSize(15);//默认画笔大小
        mDataBinding.myDrawingView.setBrush(penBrush);
        //设置画笔大小
        mDataBinding.seekbarBrushNew.setMax(50);
        mDataBinding.seekbarBrushNew.setProgress(5);
        mDataBinding.seekbarBrushNew.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                paintWidth = 5 + i * 2;
                penBrush.setSize(paintWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //设置橡皮擦大小
        mDataBinding.seekbarEraserNew.setMax(50);
        mDataBinding.seekbarEraserNew.setProgress(5);
        mDataBinding.seekbarEraserNew.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                eraserWidth = 5 + i * 2;
                penBrush.setSize(eraserWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //初始化画笔
    private void initPen() {
        penBrush = PenBrush.defaultBrush();
        penBrush.setColor(Color.parseColor("#333333"));//默认画笔颜色
        penBrush.setSize(15);//默认画笔大小
        mDataBinding.myDrawingView.setBrush(penBrush);
        //设置画笔大小
        mDataBinding.seekbarBrush.setMax(50);
        mDataBinding.seekbarBrush.setProgress(5);
        mDataBinding.seekbarBrush.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                paintWidth = 5 + i * 2;
                penBrush.setSize(paintWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //设置橡皮擦大小
        mDataBinding.seekbarEraser.setMax(50);
        mDataBinding.seekbarEraser.setProgress(5);
        mDataBinding.seekbarEraser.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                eraserWidth = 5 + i * 2;
                penBrush.setSize(eraserWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.save_ing));
        if (type == 1) {
            mDataBinding.ivDrawImgBg.setVisibility(View.GONE);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.rlDrawSave);
                        //保存到相册
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        //保存到历史记录
                        if (type == 0) {
                            String filePath = FileUtil.generateFilePath(Content.MyHomeRecord, ".png");
                            ImageUtils.save(bitmap, filePath, Bitmap.CompressFormat.PNG);
                        } else if (type == 1) {
                            String filePath = FileUtil.generateFilePath(Content.MyDrawRecord, ".png");
                            ImageUtils.save(bitmap, filePath, Bitmap.CompressFormat.PNG);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_to_album);
                        finish();
                    }
                });
            }
        }, 1000);
    }

    private void clearSelectionNew() {
        mDataBinding.seekbarBrushNew.setVisibility(View.GONE);
        mDataBinding.seekbarEraserNew.setVisibility(View.GONE);
        mDataBinding.llColorSelNew.setVisibility(View.GONE);
        mDataBinding.llBgColorSel.setVisibility(View.GONE);
    }

    private void clearSelection() {
        mDataBinding.seekbarBrush.setVisibility(View.GONE);
        mDataBinding.seekbarEraser.setVisibility(View.GONE);
        mDataBinding.llColorSel.setVisibility(View.GONE);
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.TOP);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 200;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView save = inflate.findViewById(R.id.ivDialogTipSave);
        ImageView exit = inflate.findViewById(R.id.ivDialogTipExit);
        ImageView cancel = inflate.findViewById(R.id.ivDialogTipCancel);
        save.setOnClickListener(this);
        exit.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

}